package com.wj.facedetect.activity.login;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.wj.facedetect.R;
import com.wj.facedetect.activity.base.MainActivity;
import com.wj.facedetect.bean.login.GetUserIdBean;
import com.wj.facedetect.bean.login.LoginBean;
import com.wj.facedetect.commom.FaceDetectApplication;
import com.wj.facedetect.presenter.LoginPresenter;
import com.wj.facedetect.service.PollingService;
import com.wj.facedetect.util.CommonUtils;
import com.wj.facedetect.util.DialogUtil;
import com.wj.facedetect.util.PreferencesUtils;
import com.wj.facedetect.util.ToastUtil;
import com.wj.facedetect.view.IBaseView;
import com.wj.facedetect.widget.LoadingDialog;
import com.wj.facedetect.widget.MyEditText;

public class LoginActivity extends AppCompatActivity implements IBaseView {
    private MyEditText etAccount, etPwd;
    private LoginPresenter loginPresenter;
    private LoadingDialog loadingDialog;
    private TextView tvSettingIp;
    private final static int REQ_WHAT_LOGIN = 0X001;
    private final static int REQ_WHAT_JQ = REQ_WHAT_LOGIN + 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //按Android SDK版本不同设置状态栏沉浸颜色r
        FaceDetectApplication.getApplication().addActivity(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
            //First translucent status bar.
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int statusBarHeight = CommonUtils.getStatusBarHeight(this);

            View mChildView = mContentView.getChildAt(0);
            if (mChildView != null) {
                FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mChildView.getLayoutParams();
                //如果已经为 ChildView 设置过了 marginTop, 再次调用时直接跳过
                if (lp != null && lp.topMargin < statusBarHeight && lp.height != statusBarHeight) {
                    //不预留系统空间
                    ViewCompat.setFitsSystemWindows(mChildView, false);
                    lp.topMargin += statusBarHeight;
                    mChildView.setLayoutParams(lp);
                }
            }

            View statusBarView = mContentView.getChildAt(0);
            if (statusBarView != null && statusBarView.getLayoutParams() != null && statusBarView.getLayoutParams().height == statusBarHeight) {
                //避免重复调用时多次添加 View
                statusBarView.setBackgroundColor(getResources().getColor(R.color.head_color));
                return;
            }
            statusBarView = new View(this);
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight);
            statusBarView.setBackgroundColor(getResources().getColor(R.color.head_color));
            //向 ContentView 中添加假 View
            mContentView.addView(statusBarView, 0, lp);
        } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色
            window.setStatusBarColor(getResources().getColor(R.color.head_color));

            ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
            View mChildView = mContentView.getChildAt(0);
            if (mChildView != null) {
                //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 预留出系统 View 的空间.
                ViewCompat.setFitsSystemWindows(mChildView, true);
            }
        }
        loadingDialog = new LoadingDialog(this);
        loginPresenter = new LoginPresenter(this);
        initView();
    }

    private void initView() {
        etAccount = findViewById(R.id.et_account);
        etPwd = findViewById(R.id.et_pwd);
        tvSettingIp = findViewById(R.id.tv_setting_ip);
        String account = PreferencesUtils.getInstance().getSharePreStr(PreferencesUtils.ACCOUNT);
        String pwd = PreferencesUtils.getInstance().getSharePreStr(PreferencesUtils.PWD);
        etAccount.setText(account);
        etPwd.setText(pwd);
    }

    public void settingIp(View view) {
        DialogUtil.showInputIpDialog(this, new DialogUtil.SettingIpListener() {
            @Override
            public void getIp(String zwIp, String gwIp, String clusterId) {
                PreferencesUtils.getInstance().putSharePre(PreferencesUtils.BASE_URL, zwIp);
                PreferencesUtils.getInstance().putSharePre(PreferencesUtils.GW_BASE_URL, gwIp);
                PreferencesUtils.getInstance().putSharePre(PreferencesUtils.GW_BASE_URL_APP, gwIp + "/app");
                PreferencesUtils.getInstance().putSharePre(PreferencesUtils.GW_BASE_URL_IM, gwIp + "/im");
                PreferencesUtils.getInstance().putSharePre(PreferencesUtils.CLUSTER_ID, clusterId);
            }
        });

    }

    public void login(View view) {
        String account = etAccount.getText().toString();
        String pwd = etPwd.getText().toString();
        if (TextUtils.isEmpty(account)) {
            etAccount.setError("账户不能为空");
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            etPwd.setError("密码不能为空");
            return;
        }
        if (loadingDialog != null) {
            loadingDialog.show();
        }
        PreferencesUtils.getInstance().putSharePre(PreferencesUtils.ACCOUNT, account);
        PreferencesUtils.getInstance().putSharePre(PreferencesUtils.PWD, pwd);
        loginPresenter.login(account, pwd, REQ_WHAT_LOGIN, null);
    }

    @Override
    public void onSuccess(int what, Object data, Object carryObj) {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
        switch (what) {
            case REQ_WHAT_LOGIN:
                LoginBean loginBean = (LoginBean) data;
                if (loginBean != null) {
                    if (loginBean.getRtn() == 0) {
                        //登录成功 开始鉴权
                        loginPresenter.getUserId(PreferencesUtils.getInstance().getSharePreStr(PreferencesUtils.ACCOUNT), REQ_WHAT_JQ, null);
                    } else {
                        ToastUtil.showMessage("登录失败");
                    }
                }
                break;
            case REQ_WHAT_JQ:
                //鉴权
                GetUserIdBean getUserIdBean = (GetUserIdBean) data;
                if (getUserIdBean != null) {
                    if (getUserIdBean.isSuccess()) {
                        //跳转到主页
                        Intent intent = new Intent(this, MainActivity.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.anim_in_right, R.anim.anim_out_left);
                        //开始轮询检测 告警消息
                        startService(new Intent(FaceDetectApplication.getContext(), PollingService.class));
                        finish();
                    } else {
                        ToastUtil.showMessage("鉴权失败");
                    }
                }
                break;

        }
    }

    @Override
    public void onError(int what, Exception e, Object carryObj) {
        //网络异常
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
        ToastUtil.showMessage("网络异常");
    }

    @Override
    public void onFail(int what, int errorCode, String errorMsg, Object carryObj) {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }
}
